package cn.zlp.hrm.controller;

import cn.zlp.hrm.dto.CourseDto;
import cn.zlp.hrm.service.ICourseService;
import cn.zlp.hrm.domain.Course;
import cn.zlp.hrm.query.CourseQuery;
import cn.zlp.hrm.util.AjaxResult;
import cn.zlp.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    public ICourseService courseService;


    /**
     * 保存和修改公用的
     * @param course 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody @Valid CourseDto courseDto) {
        try {
            if ( courseDto.getCourse().getId() != null){
                    courseService.updateById(courseDto);
            }
            else{
                    courseService.insert(courseDto);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败！" + e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
                courseService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败！" + e.getMessage());
        }
    }

    //获取用户
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('course:getById')")
    public Course get(@PathVariable("id") Long id) {
        return courseService.selectById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    @PreAuthorize("hasAuthority('course:get')")
    public List<Course> list() {

        return courseService.selectList(null);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<Course> json(@RequestBody CourseQuery query) {
        return courseService.selectPageList(query);
    }

    /**
     * 课程上线
     * @param ids
     * @return
     */
    @PostMapping("/online")
    @PreAuthorize("hasAuthority('course:online')")
    public AjaxResult online(@RequestBody List<Long> ids) {
        return courseService.online(ids);
    }

    /**
     * 课程下线
     * @param ids
     * @return
     */
    @PostMapping("/offline")
    @PreAuthorize("hasAuthority('course:offline')")
    public AjaxResult offline(@RequestBody List<Long> ids) {
        return courseService.offline(ids);
    }
}
